package cn.jn.lhm.netty.part01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/4/19 - 23:40
 **/
@Slf4j
public class HelloServer {
    public static void main(String[] args) {
        // 服务端启动器
        new ServerBootstrap()
                // 事件监听组
                .group(new NioEventLoopGroup())
                // 选择服务端的 ServerSocketChannel 实现
                .channel(NioServerSocketChannel.class)
                // boss 负责处理连接，worker（child）负责处理读写
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        // 将 bytebuf 转为字符串
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                // 打印上一步处理完成的 msg
                                log.info(msg.toString());
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
